<template>
  <div class="dormitory-pie-chart">
    <div v-loading="loading" ref="chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getDormitoryStats } from '@/api/stuinfo/attendancerecord';

export default {
  name: 'DormitoryPieChart',
  data() {
    return {
      chart: null,
      loading: false,
      statsData: {
        normal: 0,    // 正常归宿
        late: 0,      // 晚归
        absent: 0     // 不归
      }
    };
  },
  mounted() {
    this.initChart();
    this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
async fetchData() {
  this.loading = true;
  try {
    const res = await getDormitoryStats();
    console.log('API响应:', res); // 调试日志
    
    // 确保从正确的字段获取数据
    const responseData = res.data || res;
    
    this.statsData = {
      normal: responseData.normal || 0,
      late: responseData.late || 0,
      absent: responseData.absent || 0
    };
    
    this.updateChart();
  } catch (error) {
    console.error('获取宿舍数据失败:', error);
    this.$message.error('获取数据失败，请稍后重试');
    // 开发阶段可暂时使用模拟数据
    this.statsData = {
      normal: 285,
      late: 32,
      absent: 8
    };
    this.updateChart();
  } finally {
    this.loading = false;
  }
},
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      this.updateChart();
    },
    updateChart() {
      const total = this.statsData.normal + this.statsData.late + this.statsData.absent;
      const option = {
        title: {
          text: '学生归宿情况统计',
          subtext: total > 0 ? `总记录数: ${total}` : '暂无数据',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `${params.name}<br/>数量: ${params.value} (${params.percent}%)`;
          }
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['正常归宿', '晚归学生', '未归学生']
        },
        series: [
          {
            name: '归宿情况',
            type: 'pie',
            radius: ['50%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: [
              {
                value: this.statsData.normal,
                name: '正常归宿',
                itemStyle: { color: '#67C23A' }
              },
              {
                value: this.statsData.late,
                name: '晚归学生',
                itemStyle: { color: '#E6A23C' }
              },
              {
                value: this.statsData.absent,
                name: '未归学生',
                itemStyle: { color: '#F56C6C' }
              }
            ]
          }
        ]
      };
      this.chart.setOption(option);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  }
};
</script>

<style scoped>
.dormitory-pie-chart {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
</style>